package com.ruoqing.inform.service.impl;

import com.ruoqing.inform.service.api.MailMessageService;
import com.sun.mail.util.MailSSLSocketFactory;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
	* @author YaoXian
	* @title: MailMessageServiceImpl
	* @projectName ruoxi-blog
	* @description: 若兮微服务 - 通知服务 - 发送QQ邮件
	* @date 2020-11-05 13:11
	*/
@RestController
@Slf4j
public class MailMessageServiceImpl implements MailMessageService {
		
		@ApiOperation(value = "发送QQ邮件", httpMethod = "GET")
		@Override
		@ApiImplicitParams(value = {@ApiImplicitParam(name = "sender", value = "发件人"
						, required = true, dataType = "String"),@ApiImplicitParam(name = "receiver", value = "收件人"
						, required = true, dataType = "String"),@ApiImplicitParam(name = "emailTitle", value = "邮件标题"
						, required = true, dataType = "String"),@ApiImplicitParam(name = "messageBody", value = "邮件内容"
						, required = true, dataType = "String")})
		public String sendMailMessage(String sender, String receiver, String emailTitle, String messageBody) throws Exception {
				// 执行结果
				String msg;
				// 指定发送邮件的主机为 smtp.qq.com
				//QQ 邮件服务器
				String host = "smtp.qq.com";
				// 获取系统属性
				Properties properties = System.getProperties();
				// 设置邮件服务器
				properties.setProperty("mail.smtp.host", host);
				properties.put("mail.smtp.auth", "true");
				MailSSLSocketFactory sf = new MailSSLSocketFactory();
				sf.setTrustAllHosts(true);
				properties.put("mail.smtp.ssl.enable", "true");
				properties.put("mail.smtp.ssl.socketFactory", sf);
				// 获取默认session对象 填写QQ邮箱授权码
				Session session = Session.getDefaultInstance(properties,new Authenticator(){
						@Override
						public PasswordAuthentication getPasswordAuthentication()
						{
								return new PasswordAuthentication("2625697531@qq.com", "tzhygpozkbnaechg");
						}
				});
				try{
						// 创建默认的 MimeMessage 对象
						MimeMessage message = new MimeMessage(session);
						// Set From: 头部头字段
						message.setFrom(new InternetAddress(sender));
						// Set To: 头部头字段
						message.addRecipient(Message.RecipientType.TO, new InternetAddress(receiver));
						// Set Subject: 头部头字段
						message.setSubject(emailTitle);
						// 设置消息体
						message.setText(messageBody);
						// 发送消息
						Transport.send(message);
						msg = "发送邮件成功";
						log.info(msg);
				}catch (MessagingException mex) {
						mex.printStackTrace();
						msg = "发送邮件失败";
				}
				return msg;
		}
}
